package com.idbk.chargestation.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.charge.ActivityGunDetail;
import com.idbk.chargestation.bean.JsonPointPile;

import java.util.List;
import java.util.Locale;

/**
 * 电桩列表专用 适配器
 *
 * @author lupc, zhx
 */
public class PileAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater mInflater;

    private List<JsonPointPile> mData;

    private ListView mListView;

    /**
     * 上次选择的
     */
    private RadioButton mPreRadioButton;

    /**
     * 当前选择项目 索引
     */
    private int mSelectedItemIndex = 0;

    private boolean mShowRadioButton = false;

    private OnItemCheckedListener mOnItemCheckedListener;

    /**
     * 推荐的最佳预约
     */
    private int mBestPosition = -1;

    /**
     * @param context         context
     * @param data            JsonPointPile的list列表
     * @param listview        listview
     * @param showRadioButton 是否显示 RadioButton
     */
    public PileAdapter(Context context, List<JsonPointPile> data, ListView listview, boolean showRadioButton) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);

        mData = data;
        mListView = listview;

        mPreRadioButton = null;

        mShowRadioButton = showRadioButton;

        chooseStyle(showRadioButton);
    }

    public PileAdapter(Context context, List<JsonPointPile> list, ListView listview) {
        this(context, list, listview, false);
    }

    private void chooseStyle(boolean showRadioButton) {
        if (showRadioButton) {
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {

                    selectItem(position, view);
                }

            });

            //计算出 推荐电桩
            calculateBestOne();
        } else {
            //显示 电桩 相关信息，主要是资费信息
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    JsonPointPile data = mData.get(position);
                    if (data.tariff != null) {
                        if (mData.get(position).gunInfos.size() <= 2) {
                            String str = data.pileInfor();
                            new AlertDialog.Builder(mContext)
                                    .setMessage(Html.fromHtml(str))
                                    .setCancelable(true)
                                    .setNegativeButton(R.string.common_ok, null)
                                    .create()
                                    .show();
                        } else {
                            Intent intent = new Intent(mContext, ActivityGunDetail.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("gunInfor", data);
                            intent.putExtras(bundle);
                            mContext.startActivity(intent);
                        }
                    }else {
                        String str = data.pileInfor();
                        new AlertDialog.Builder(mContext)
                                .setMessage(Html.fromHtml(str))
                                .setCancelable(true)
                                .setNegativeButton(R.string.common_ok, null)
                                .create()
                                .show();
                    }
                }
            });
        }
    }

    private void selectItem(int position, View view) {
        //记录当前选择
        mSelectedItemIndex = position;

        if (mPreRadioButton != null) {
            mPreRadioButton.setChecked(false);
        }

        RadioButton rb = (RadioButton) view.findViewById(R.id.radiobutton);
        rb.setChecked(true);

        mPreRadioButton = rb;

        onItemChecked(mData.get(position));
    }

//    public int getBestOne() {
//        return mBestPosition;
//    }

    /**
     * 计算出 系统推荐电桩，并将该电桩放到首位
     */
    private void calculateBestOne() {
        mBestPosition = 0;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class Holder {
        private LinearLayout mLayoutPileBlock;
        private TextView mTextPileIndex;
        private LinearLayout mLayoutPileStatus;
        private TextView mTextPileStatus;
        private ImageView mImagePileStatus;
        private TextView mTextPileSn;
        private TextView mTextPileType;
        private TextView mTextPileFee;
        private TextView mTextPileFree;
        private ImageView mImagePileTag;
        private RadioButton mRadioPileSelect;
        private RelativeLayout mRelativeFree;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v;
        Holder hold;
        if (convertView == null) {
            v = mInflater.inflate(R.layout.item_pile    , parent, false);
            hold = new Holder();

            hold.mLayoutPileBlock = (LinearLayout) v.findViewById(R.id.layout_pile_block);
            hold.mRelativeFree = (RelativeLayout) v.findViewById(R.id.relative_free);

            hold.mTextPileIndex = (TextView) v.findViewById(R.id.textview_index);

            hold.mLayoutPileStatus = (LinearLayout) v.findViewById(R.id.layout_pile_status);
            hold.mImagePileStatus = (ImageView) v.findViewById(R.id.imageview_pile_status);
            hold.mTextPileStatus = (TextView) v.findViewById(R.id.textview_pile_status);

            hold.mTextPileSn = (TextView) v.findViewById(R.id.textview_pile_sn);
            hold.mTextPileType = (TextView) v.findViewById(R.id.textview_pile_type);
            hold.mTextPileFee = (TextView) v.findViewById(R.id.textview_pile_method);
            hold.mTextPileFree = (TextView) v.findViewById(R.id.textview_pile_free);
            hold.mRadioPileSelect = (RadioButton) v.findViewById(R.id.radiobutton);

            hold.mImagePileTag = (ImageView) v.findViewById(R.id.imageview_pile_tag);


            v.setTag(hold);
        } else {
            v = convertView;
            hold = (Holder) v.getTag();
        }

        bindView(hold, position);

        return v;
    }

    private void bindView(Holder hold, int position) {
        final JsonPointPile item = mData.get(position);
        int num,free = 0;

        if (position < 100) {
            hold.mTextPileIndex.setText(String.format(Locale.CHINA, "#%02d", position + 1));
        } else {
            String p = (position + 1) + "";
            hold.mTextPileIndex.setText(p);
        }

        if (item.isEnabled) {
            PileAdapter.setPileStatus(hold, item.pileStatue);
        } else {
            hold.mTextPileStatus.setText("禁用");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_gray);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_not_be_use);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_gray);
        }

        if (item.tariff != null) {
            num = item.gunInfos.size();
            for (int i = 0; i < num; i++) {
                if (item.gunInfos.get(i).gunStatus == 3) {
                    free++;
                }
            }
            hold.mTextPileFree.setText(free + "/" + num);
            hold.mTextPileFee.setText(Html.fromHtml("收费方式 : " + item.getInfor()));
        }else{
            hold.mRelativeFree.setVisibility(View.GONE);
            hold.mTextPileFee.setText(Html.fromHtml("收费方式 : " + getPilePrice(item)));
        }
        hold.mTextPileSn.setText("电桩序列号 : " + " " + item.pileSn);
        hold.mTextPileType.setText("电桩类型 : " + " " + item.performance);

        if (!mShowRadioButton) {
            hold.mRadioPileSelect.setVisibility(View.GONE);
        } else if (position == mSelectedItemIndex) {
            hold.mRadioPileSelect.setChecked(true);
        } else {
            hold.mRadioPileSelect.setChecked(false);
        }
        //记录
        if (mPreRadioButton == null) {
            mPreRadioButton = hold.mRadioPileSelect;
        }

        //如果显示了radio，则表明是要选择预约的电桩，系统自动选择一个最佳的
        if (mShowRadioButton) {
            if (position == mBestPosition) {
                hold.mImagePileTag.setVisibility(View.VISIBLE);
                hold.mImagePileTag.setImageResource(R.drawable.ico_map_pile_recommend);
            } else {
                hold.mImagePileTag.setVisibility(View.GONE);
            }
        } else {
            //表示只是单独的电桩 列表显示
            if (item.bookAvailable) {
                hold.mImagePileTag.setVisibility(View.VISIBLE);
                hold.mImagePileTag.setImageResource(R.drawable.ico_map_pile_can_booking);
            } else {
                hold.mImagePileTag.setVisibility(View.GONE);
            }
        }
    }

    private void onItemChecked(JsonPointPile item) {
        if (mOnItemCheckedListener != null) {
            mOnItemCheckedListener.onItemChecked(item);
        }
    }

    public void addOnItemCheckedListener(OnItemCheckedListener o) {
        mOnItemCheckedListener = o;
    }

    private static void setPileStatus(Holder hold, int status) {
        //故障
        if (status == JsonPointPile.PILE_FAULT) {
            hold.mTextPileStatus.setText("故障");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_gray);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_not_be_use);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_gray);
        }
        //告警
        else if (status == JsonPointPile.PILE_WARN) {
            hold.mTextPileStatus.setText("告警");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_gray);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_not_be_use);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_gray);
        }
        //空闲
        else if (status == JsonPointPile.PILE_IDLE) {
            hold.mTextPileStatus.setText("空闲");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_green);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_free);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_green);
        }
        //充电中
        else if (status == JsonPointPile.PILE_CHARGING) {
            hold.mTextPileStatus.setText("充电中");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_red);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_charging);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_red);
        }
        //完成
        else if (status == JsonPointPile.PILE_FINISH) {
            hold.mTextPileStatus.setText("完成");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_red);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_complete);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_red);
        }
        //预约中
        else if (status == JsonPointPile.PILE_BESPEAK) {
            hold.mTextPileStatus.setText("预约中");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_gray);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_not_be_use);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_gray);
        }
        //等待
        else if (status == JsonPointPile.PILE_WAIT) {
            hold.mTextPileStatus.setText("等待");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_red);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_waitting);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_red);
        }
        //离线
        else if (status == JsonPointPile.PILE_OFFLINE) {
            hold.mTextPileStatus.setText("离线");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_gray);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_not_be_use);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_gray);
        }
        //其他
        else {
            hold.mTextPileStatus.setText("离线");
            hold.mLayoutPileStatus.setBackgroundResource(R.drawable.border_sub_gray);
            hold.mImagePileStatus.setImageResource(R.drawable.ico_map_pile_status_not_be_use);
            hold.mLayoutPileBlock.setBackgroundResource(R.drawable.border_gray);
        }
    }

    private static String getPilePrice(JsonPointPile item) {
        if (item.priceTypeEnum == JsonPointPile.PRICE_TYPE_NORMAL) {
            if (item.tariff == null) {
                return "通用电价，资费未知";
            } else {
                return "通用电价，<font color='red'>" + item.tariff.getCommonPriceString() + "</font>元/度";
            }
        } else if (item.priceTypeEnum == JsonPointPile.PRICE_TYPE_TIME) {
            return "分时电价";
        } else {
            return "N/A";
        }
    }

    public interface OnItemCheckedListener {

        void onItemChecked(JsonPointPile item);

    }

}
